//
//  HomeVC.m
//  TMSDriver
//
//  Created by mac on 2019/5/15.
//  Copyright © 2019年 zhuchongjin. All rights reserved.
//

#import "HomeVC.h"
#import <WZLBadge/WZLBadgeImport.h>
#import <SDCycleScrollView.h>
#import "FHCTopLineView.h"
#import "SendGoodsVC.h"
#import "MyAccountInforVC.h"
#import "DataStatisticsVC.h"
#import "MessageVC.h"
#import "FreightIndexListVC.h"
#import "HomeNewSourceListCell.h"
#import "HomeNewSourceListModel.h"
#import "CarSourcesRecommendVC.h"
#import "CJWKWebViewVC.h"
#import "MyAccountInforVCNew.h"
#import "CJAppInfo.h"
#import <JhtMarquee/JhtVerticalMarquee.h>
#import <JhtMarquee/JhtHorizontalMarquee.h>
#import "LineItemController.h"
#import "CJWKWebViewVC.h"
#import "ChangePasswordView.h"
#import "SafePhoneCodeController.h"
@interface HomeVC ()<SDCycleScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) CJView *viewHeader;
@property (strong,nonatomic)NSArray *localImages;
@property (strong,nonatomic)SDCycleScrollView *cycleScrollView;
@property (nonatomic,strong) CJView *viewTopLineMsg; //
@property (nonatomic,strong) JhtVerticalMarquee *verticalMarquee;
@property (nonatomic,strong) FlexFrameView *viewTapTopTouchs;
@property (nonatomic,strong) CJView *viewMore;
@property (nonatomic,strong) CJTableView *tableView;
@property (strong, nonatomic) NSMutableArray *arrNewsList;
//@property (nonatomic,strong) HomeNewSourceListCell *homeNewSourceListCell;
@property (nonatomic,strong) NSMutableArray *arrMutaBannerList;
//@property (nonatomic,strong) CJLabel *labSum;
@property (nonatomic,strong) FlexTouchView *touchViewMsg;
@property (nonatomic,strong) UIImageView *imgVMsg;
@property (nonatomic, strong) ChangePasswordView *changView;
@end

@implementation HomeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [self setSearchBarOnImg];
    [self setTitleName:[CJAppInfo appName]];
    [self setRightImage:CJLString(@"客服") image:@""];
//    self.homeNewSourceListCell = [[HomeNewSourceListCell alloc]initWithFlex:nil reuseIdentifier:nil];
    [self createUI];
}
- (ChangePasswordView *)changView{
    if (_changView == nil) {
        self.changView = [[ChangePasswordView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [self.changView.gotoInfoButton addTarget:self action:@selector(gotoInfoButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _changView;
}
- (void)gotoInfoButtonAction{
    [self.changView removeFromSuperview];
    SafePhoneCodeController *vc = [[SafePhoneCodeController alloc] init];
    vc.isQChangePassword = @"1";
    [self pushVc:vc];
}
- (void)HomeIsChangePassword{
    NSDictionary *dic = CJFetchMyDefault(CJPartyUserCenter);
    if (dic) {
        if ([dic[@"isModifyPwd"] intValue] == 0) {
            [[UIApplication sharedApplication].keyWindow addSubview: self.changView];
        }
    }
}
- (void)createUI{
    
    [self.viewHeader addSubview:self.cycleScrollView];
    [self.viewHeader addSubview:self.viewTopLineMsg];
    [self.viewHeader addSubview:self.verticalMarquee];
    [self createHomeTapsView];
    [self.viewHeader addSubview:self.viewMore];
    [self.view addSubview:self.tableView];
    [self setTapHeaderAction];
    CJRegisterNotify(JpushMsgSum, @selector(getMessageSum));
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    [self getBrachcCode];
    if ([CJControl isLogin]) {
        [self loadData];
        [self loadNewsListData];
        [self getMessageSum];
    }
    [self loadCycleScrollViewData];
    self.image.backgroundColor = [UIColor cjWhiteColor];
    [self HomeIsChangePassword];

}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"HomeIsChangePassword" object:nil];
}
- (void)getMessageSum{
    WS(ws);
    [CJNetWork getHomeVCMessageNoReadSumSuccess:^(id  _Nullable responseObject) {

        NSString *strNum = (NSString *)responseObject;

        if (strNum.intValue <= 0) {
            [ws.imgVMsg clearBadge];
          }else{
           [ws.imgVMsg showBadgeWithStyle:WBadgeStyleNumber value:strNum.intValue animationType:WBadgeAnimTypeNone];
          }
    }];
}

- (void)createHomeTapsView{
    
    [self.viewTapTopTouchs removeAllSubviews];
    CGRect rcFrame = CGRectMake(0, self.viewTopLineMsg.bottom + CJToViewMarginH, [[UIScreen mainScreen] bounds].size.width, 0);
    self.viewTapTopTouchs = [[FlexFrameView alloc] initWithFlex:[CJControl getUIWithNew] ? @"HomeTapTouchViewsNew":@"HomeTapTouchViews" Frame:rcFrame Owner:self];
    self.viewTapTopTouchs.flexibleHeight = YES;
    
    [self.viewTapTopTouchs layoutIfNeeded];
    [self.viewHeader addSubview:self.viewTapTopTouchs];
    
    if ([CJControl isLogin]) {
        [self getMessageSum];
    }
    
}

- (void)getBrachcCode{
    WS(ws);
    [CJNetWork getBrachcCodeSuccess:^(id  _Nullable responseObject) {
        [ws createHomeTapsView];
        ws.viewMore.frame = CGRectMake(0, self.viewTapTopTouchs.bottom, SCREEN_WIDTH, LW(50));
        self.viewHeader.height = self.cycleScrollView.height + self.viewTopLineMsg.height + self.viewTapTopTouchs.height + self.viewMore.height + CJToViewMarginH*2;
        [ws.tableView reloadData];
    }];
}
- (void)RightTextClick:(UIButton *)sender{
    CJWKWebViewVC *vc = [CJWKWebViewVC new];
    vc.strTitle = @"客服";
    vc.useUTF8 = YES;
    vc.kefu = @"1";
    vc.strUrl = @"https://huanxin.deskpro.cn/webim/im.html?configId=b04d6591-d151-4825-a74e-6d584feeef09&restServer=hxim.deskpro.cn&xmppServer=scim.deskpro.cn";
    [self pushVc:vc];
}

- (void)setTapHeaderAction{
    WS(ws);
    // 更多
    [self.viewMore setTapActionWithBlock:^{
        FreightIndexListVC *vc = [FreightIndexListVC new];
        [ws pushVc:vc];
    }];
}

#pragma mark ----------中间四个功能按钮的Action

/// <#Description#>
- (void)btnTouchViewHomeSendGoodsAction{
    
//    if ([CJControl isLogin]) {
//        SendGoodsVC *vc = [SendGoodsVC new];
//        [self pushVc:vc];
//    }else{
//        [self showLoginWindowALert];
//    }
    if ([CJControl isLogin]) {
        LineItemController *vc = [LineItemController new];
        [self pushVc:vc];
    }else{
        [self showLoginWindowALert];
    }
}

/// <#Description#>
- (void)btnTouchViewHomeAccontInfoAction{

    if ([CJControl isLogin]) {

        if ([CJControl getUIWithNew]) {
            MyAccountInforVCNew *vc = [MyAccountInforVCNew new];
            [self pushVc:vc];
        }else{
            MyAccountInforVC *vc = [MyAccountInforVC new];
            [self pushVc:vc];
        }
    }else{
        
        [self showLoginWindowALert];
    }
    
}

/// <#Description#>
- (void)btnTouchViewHomeTongjiAction{
    
    if ([CJControl isLogin]) {
        DataStatisticsVC *vc = [DataStatisticsVC new];
        [self pushVc:vc];
    }else{
        [self showLoginWindowALert];
    }

}

/// <#Description#>
- (void)btnTouchViewHomeMessageAction{
    
    if ([CJControl isLogin]) {
    
        MessageVC *vc = [MessageVC new];
        [self pushVc:vc];
    }else{
        [self showLoginWindowALert];
    }
}

/// 轮播图数据
- (void)loadCycleScrollViewData{
    
    NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/banner",CJBaseUrl);
    NSDictionary *dicPra = @{@"type":@"shippment", //
                             @"branchCode":[CJControl getBranchCode],
                             @"status":@"0"
    };
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strUrl parameters:dicPra success:^(id  _Nonnull responseObject) {
        
//        DLog(@"++++++++%@",responseObject);
        NSMutableArray *arrTitle = [[NSMutableArray alloc]init];
        NSArray *list = responseObject[@"records"];
           [ws.arrMutaBannerList removeAllObjects];
        if (list.count == 0) {
            _cycleScrollView.localizationImageNamesGroup = self.localImages;

        }else{
            for (int i = 0; i<list.count; i++) {
                NSDictionary *dic = list[i];
                [arrTitle addObject:dic[@"img"]];
            }
            _cycleScrollView.imageURLStringsGroup = arrTitle;
            [ws.arrMutaBannerList addObjectsFromArray:list];
        }
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        
    }];

}

/// 新闻列表
- (void)loadNewsListData{
   
    NSString *strUrl = CJStringWithFormat(@"%@/ntocc-tms-api/vehicleSource",CJBaseUrl);
    NSDictionary *dicPra = @{@"pageNum":@"1",
                             @"pageSize":@"10",
                             @"branchCode":[CJControl getBranchCode]
                            };
    WS(ws);
    NSMutableArray *arrTitle = [[NSMutableArray alloc]init];
    
    [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:GetType url:strUrl parameters:dicPra status:ArpaDefault success:^(id  _Nonnull responseObject) {
        
        NSArray *list = responseObject[@"records"];
        
        if (list.count > 0) {

            for (int i = 0; i<list.count; i++) {
                NSDictionary *dic = list[i];
                [arrTitle addObject:CJStringWithFormat(@"%@ -> %@",dic[@"departure"],dic[@"destination"])];
            }
            ws.verticalMarquee.sourceArray = arrTitle;

        }else{
            ws.verticalMarquee.sourceArray = @[@"暂无推荐",@"暂无推荐"];
        }
        [ws.verticalMarquee marqueeOfSettingWithState:MarqueeStart_V];

    } failure:^(NSError * _Nonnull error) {
        ws.verticalMarquee.sourceArray = @[@"暂无推荐",@"暂无推荐"];
        [ws.verticalMarquee marqueeOfSettingWithState:MarqueeStart_V];
    }];
    
}

/// <#Description#>
- (void)loadData{

    NSString *strUrl = CJStringWithFormat(@"%@/ntocc-tms-api/order/orderFreightIndexList",CJBaseUrl);
    NSDictionary *dicPar = @{
                         @"pageSize":@"10",
                        };
    //
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strUrl parameters:dicPar success:^(id  _Nonnull responseObject) {

        NSArray *list = responseObject[@"records"];
        //            if (list.count > 0) {
        [ws.arrNewsList removeAllObjects];
        NSError * error ;
        NSArray *arr = [HomeNewSourceListModel arrayOfModelsFromDictionaries:list error:&error];
        [ws.arrNewsList addObjectsFromArray:arr];
        [ws.tableView reloadData];

    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);

    }];

}

#pragma mark----tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrNewsList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *identifier = @"HomeNewSourceListCell";
     HomeNewSourceListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
     if (cell == nil) {
         cell = [[HomeNewSourceListCell alloc] initWithFlex:[CJControl getUIWithNew] ? @"HomeNewSourceListCellNew":@"HomeNewSourceListCell" reuseIdentifier:identifier];
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
     }
    HomeNewSourceListModel *model = self.arrNewsList[indexPath.row];
    [cell setCellInfoWithModel:model];
    return cell;
}

/**
 *  轮播本地图片
 */
#pragma mark - SDCycleScrollView代理方法
/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    DLog(@"SDCycleScrollView 点击图片回调== %ld",index);
    
    if (self.arrMutaBannerList.count >= index) {
        NSDictionary *dic = self.arrMutaBannerList[index];
        CJWKWebViewVC *vc  =  [[CJWKWebViewVC alloc]init];
        vc.strUrl = [CJControl getThreeUnaryValueStr:dic[@"url"]];
        vc.strTitle = [CJControl getThreeUnaryValueStr:dic[@"title"]];
       
       if ([CJControl getIsEmpty:dic[@"url"]]) {
           
       }else{
          [self pushVc:vc];
       }
    }
    
}

/** 图片滚动回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index{
    //     DLog(@"SDCycleScrollView 图片滚动回调== %ld",index)
}


#pragma mark -  纵向跑马灯
/** 点击 滚动跑马灯 触发方法 */
- (void)marqueeTapGes:(UITapGestureRecognizer *)ges {
    CarSourcesRecommendVC *vc = [[CarSourcesRecommendVC alloc]init];
    [self pushVc:vc];
}

#pragma mark ----------lazy
- (CJView *)viewHeader{
    if (!_viewHeader) {
        _viewHeader = CJView.viewInit
        .viewFrame(CGRectMake(0, 0, SCREEN_WIDTH, LW(0)))
        .viewbgColor([UIColor cjBackgroundColor])
        ;
    }
    return _viewHeader;
}

// 轮播图
- (NSArray *)localImages{
    
    if (!_localImages) {
        _localImages = @[@"zcj_banner01"];
    }
    return _localImages;
}
- (SDCycleScrollView *)cycleScrollView{
    if (!_cycleScrollView) {
        CGRect rect = CGRectMake(0*CJToLeftMargin,0, SCREEN_WIDTH - 0*CJToLeftMargin, LW(135));
        _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:rect imageNamesGroup:self.localImages];
//        _cycleScrollView.backgroundColor = [UIColor cjWhiteColor];
        //设置图片视图显示类型
        _cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleToFill;
        //设置轮播视图的分页控件的显示
        _cycleScrollView.showPageControl = YES;
        _cycleScrollView.delegate = self;
        //设置轮播视图分也控件的位置
        _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        //当前分页控件小圆标颜色
        _cycleScrollView.currentPageDotColor = [UIColor cjWhiteColor];
        //其他分页控件小圆标颜色
        _cycleScrollView.pageDotColor = [UIColor cjLightGrayColor];
    }
    return  _cycleScrollView;
}

// topLineView
- (CJView *)viewTopLineMsg{
    if (!_viewTopLineMsg) {
        _viewTopLineMsg = CJView.viewInit
        .viewFrame(CGRectMake(0,_cycleScrollView.bottom + CJToViewMarginH, SCREEN_WIDTH, LH(40)))
        ;
        // 文字 文字和图片
        CJLabel *lab = CJLabel.labInit
        .labFrame(CGRectMake(0, 0,LW(10), _viewTopLineMsg.height))
        .labText(@"")
        .labTextColor([UIColor blackColor])
        .labBgColor([UIColor cjClearColor])
//        .labFontSize(17.0)
        .labFont([UIFont boldSystemFontOfSize:17.0])
        ;
        [_viewTopLineMsg addSubview:lab];

        CJImageView *imgV = CJImageView.imgInit
        .imgVFrame(CGRectMake(lab.right, lab.top + (lab.height - LW(25))/2 ,LW(60) ,LW(25)))
        .imgVImageName(@"zcj_tuijian")
        ;
        [_viewTopLineMsg addSubview:imgV];
        imgV.contentMode = UIViewContentModeScaleAspectFit;

        CJImageView *imgV1 = CJImageView.imgInit
           .imgVFrame(CGRectMake(SCREEN_WIDTH - LW(20), lab.top + (lab.height - LW(10))/2 ,LW(6),LW(10)))
           .imgVImageName(@"zcj_arrow_right")
           ;
        [_viewTopLineMsg addSubview:imgV1];
        
    }
    return _viewTopLineMsg;
}

- (JhtVerticalMarquee *)verticalMarquee {
    
    if (!_verticalMarquee) {
        _verticalMarquee = [[JhtVerticalMarquee alloc]  initWithFrame:CGRectMake(LW(80 + 10),_cycleScrollView.bottom + CJToViewMarginH, SCREEN_WIDTH-LW(80) - LW(30) - LW(10), LH(40))];
//        _verticalMarquee.isCounterclockwise = YES;
        _verticalMarquee.numberOfLines = 0;
        _verticalMarquee.backgroundColor = [UIColor cjWhiteColor];
        _verticalMarquee.textColor = [UIColor cjMainTextColor];
        _verticalMarquee.textFont = [UIFont cjTitleFont13];
        
        // 添加点击手势
        UITapGestureRecognizer *vtap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(marqueeTapGes:)];
        [_verticalMarquee addGestureRecognizer:vtap];
    }
    
    return _verticalMarquee;
}

//运价指数  更多
- (CJView *)viewMore{
    if (!_viewMore) {
        _viewMore = CJView.viewInit
        .viewFrame(CGRectMake(0, self.viewTapTopTouchs.bottom, SCREEN_WIDTH, LW(50)))
        ;
        CJLabel *lab = CJLabel.labInit
        .labFrame(CGRectMake(CJToLeftMargin, 0, SCREEN_WIDTH/2,_viewMore.height))
        .labText(@"运价指数")
        .labFontSize(20)
//        .labBgColor([UIColor cjRandomColor])
        ;
        [_viewMore addSubview:lab];
        CJLabel *lab1 = CJLabel.labInit
        .labFrame(CGRectMake(lab.right, 0, SCREEN_WIDTH - 2*CJToLeftMargin - lab.width - LW(20),_viewMore.height))
        .labText(@"更多  ")
        .labFontSize(14)
        .labAlignment(NSTextAlignmentRight)
        .labTextColor([UIColor cjSubheadTextColor])
//        .labBgColor([UIColor cjRandomColor])
        ;
        [_viewMore addSubview:lab1];

        CJImageView *imgV = CJImageView.imgInit
        .imgVFrame(CGRectMake(lab1.right + LW(10), (_viewMore.height - LW(10))/2, LW(6), LW(10)))
        .imgVImageName(@"zcj_arrow_right")
        ;
        [_viewMore addSubview:imgV];
//        _viewMore.backgroundColor = [UIColor cjRandomColor];
    }
    return _viewMore;
}


- (NSMutableArray *)arrNewsList{
    if (!_arrNewsList) {
        _arrNewsList = [[NSMutableArray alloc]init];
    }
    return _arrNewsList;
}
- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, kTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight - kTabBarHeight),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
//        .tbMjHeadFooter(YES)
        ;
//        WS(ws);
        self.viewHeader.height = self.cycleScrollView.height + self.viewTopLineMsg.height + self.viewTapTopTouchs.height + self.viewMore.height + CJToViewMarginH*2;
        _tableView.tableHeaderView= self.viewHeader;
    }
    return _tableView;
}

- (NSMutableArray *)arrMutaBannerList{
    if (!_arrMutaBannerList) {
        _arrMutaBannerList = [[NSMutableArray alloc]initWithCapacity:1];
    }
    return _arrMutaBannerList;
}



@end
